package com.bjpowernode.javase.collection;

import org.w3c.dom.ls.LSOutput;

import java.util.ArrayList;
import java.util.Iterator;

public class 循环删除添加list {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>(){{
            add(1);
            add(2);
            add(3);
            add(4);
            add(5);
        }};

        System.out.println("=========循环删除=================");
        /*
        方法一:for循环中删除元素，不会报错
        */
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i) == 1) arrayList.remove(i);
        }
        System.out.println("方法一");
        arrayList.forEach(System.out::println);
        /**
         * 方法2
         */
        Iterator<Integer> iterator = arrayList.iterator();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            //if (next == 2) arrayList.remove(Integer.valueOf(2)); //报错
            if (next == 2) iterator.remove();
        }
        System.out.println("方法二");
        arrayList.forEach(System.out::println);

        /**
         * 方法三:报错
         */
        for (Integer integer : arrayList) {
//            if (integer == 3) arrayList.remove(Integer.valueOf(3));
        }

        System.out.println("=========循环新增=================");
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i) == 3) arrayList.add(6);
        }
        System.out.println("新增方法1");
        arrayList.forEach(System.out::println);

        System.out.println("iterator必须重新获取");
        iterator = arrayList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("新增方法二");
        iterator = arrayList.iterator();
        /*while (iterator.hasNext()){
            if(iterator.next() == 3) arrayList.add(7); //报错
        }*/
        arrayList.forEach(System.out::println);

        System.out.println("新增方法三");
        /*arrayList.forEach(nums ->{
            if (nums == 3) arrayList.add(7);//报错
        });*/
        arrayList.forEach(System.out::println);
    }

}
